package com.prs.crm.dao.oa.impl;

import java.sql.SQLException;
import java.util.Collection;
import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.prs.crm.dao.impl.BaseDaoImpl;
import com.prs.crm.dao.oa.KnowledgeDao;
import com.prs.crm.domain.oa.Knowledge;

public class KnowledgeDaoImpl extends BaseDaoImpl<Knowledge> implements KnowledgeDao{

	@Override
	public Collection<Knowledge> getAllKnowledge() {
		// TODO Auto-generated method stub
		Criteria criteria = this.getSession().createCriteria(Knowledge.class);
		return criteria.list();
	}

	@Override
	public Collection<Knowledge> getKnowledgeByIds(Collection<Integer> ids) {
		// TODO Auto-generated method stub
		Criteria criteria = this.getSession().createCriteria(Knowledge.class);
		criteria.add(Restrictions.in("id", ids));
		criteria.addOrder(Order.desc("recordTime"));
		return criteria.list();
	}

	@Override
	public Collection<?> getReportKnowledgeSource(final Date datestart, final Date dateend) {
		// TODO Auto-generated method stub
		return (Collection<?>) this.getHibernateTemplate().execute(new HibernateCallback(){

			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				// TODO Auto-generated method stub
				Criteria criteria = arg0.createCriteria(Knowledge.class);
				if(datestart != null)
					criteria.add(Restrictions.ge("recordTime", datestart));
				if(dateend != null)
					criteria.add(Restrictions.le("recordTime", dateend));
				ProjectionList projectionlist=Projections.projectionList();  
	        	projectionlist.add(Projections.groupProperty("type"));
	        	projectionlist.add(Projections.rowCount());
	        	criteria.setProjection(projectionlist);
				return criteria.list();
			}});
	}

}
